<template>
  <div class="order-page">
    <!-- 统计卡片区域 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card shadow="always" class="stat-card total-card">
            <el-statistic :value="orderStats.totalCount">
              <template #title>
                <div style="display: inline-flex; align-items: center">总订单数</div>
              </template>
              <template #suffix>
                <span style="font-size: 12px; color: #6b7280">个订单</span>
              </template>
            </el-statistic>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card shadow="always" class="stat-card amount-card">
            <el-statistic :value="formatPrice(orderStats.totalAmount)" :precision="2">
              <template #title>
                <div style="display: inline-flex; align-items: center">总金额</div>
              </template>
              <template #prefix>
                <span style="font-size: 16px; color: #67c23a">¥</span>
              </template>
              <template #suffix>
                <span style="font-size: 12px; color: #6b7280">元</span>
              </template>
            </el-statistic>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 筛选和搜索区域 -->
    <div class="filters-section">
      <el-form :model="searchForm" :inline="true">
        <el-form-item label="订单编号:">
          <el-input
            v-model="searchOptions.orderNo"
            placeholder="请输入订单编号"
            style="width: 200px"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="康复师姓名:">
          <el-input
            v-model="searchOptions.doctorName"
            placeholder="请输入康复师姓名"
            style="width: 200px"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="订单状态:">
          <el-select
            v-model="searchOptions.reservationStatus"
            style="width: 150px"
            placeholder="请选择状态"
            @change="handleSearch"
          >
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格区域 -->
    <div class="table-section">
      <el-card>
        <div class="table-header">
          <h3>订单管理列表共{{ pagination.total }}条记录</h3>
          <el-button type="primary" plain @click="handleRefresh">
            <el-icon><Refresh /></el-icon>
            刷新数据
          </el-button>
        </div>

        <el-table :data="tableData" height="500" style="width: 100%; margin-top: 10px" v-loading="loading">
          <el-table-column prop="orderNo" label="订单编号" min-width="200">
            <template #default="scope">
              <span style="font-weight: 500">{{ scope.row.orderNo }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="康复师" min-width="150">
            <template #default="scope">
              <el-space>
                <el-avatar size="medium" :src="scope.row.avatar" />
                <span>{{ scope.row.username }}</span>
              </el-space>
            </template>
          </el-table-column>
          <el-table-column prop="updateTime" label="状态更新时间" min-width="150">
            <template #default="scope">
              {{ formatDateTime(scope.row.updateTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="totalAmount" label="订单金额" min-width="120">
            <template #default="scope">
              <span style="font-weight: 600; color: #67c23a">¥{{ formatPrice(scope.row.totalAmount) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="reservationStatus" label="状态" min-width="100">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.reservationStatus)">{{
                getStatusText(scope.row.reservationStatus)
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" fixed="right">
            <template #default="scope">
              <div class="operation-buttons">
                <el-button size="small" @click="handleView(scope.row)">查看</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页部分 -->
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          style="margin-top: 20px"
          :page-sizes="[5, 10, 20, 30, 40]"
          size="default"
          layout="total, sizes, prev, pager, next"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-card>
    </div>

    <!-- 订单详情组件 -->
    <OrderDetail v-model="detailVisible" :order-data="currentOrder" @close="handleDetailClose" />
  </div>
</template>

<script setup lang="ts">
import type { OrderRequest, OrderResponse, OrderStats } from '@/api/model/orderModel';
import { getOrderDetail, getOrderList, getOrderStats } from '@/api/order';
import { formatDateTime } from '@/utils/date';
import { ElMessage } from 'element-plus';
import { defineAsyncComponent, onActivated, ref, watch } from 'vue';

// 动态导入订单详情组件
const OrderDetail = defineAsyncComponent(() => import('@/components/OrderDetail/index.vue'));

defineOptions({
  name: 'OrderIndex',
});

// 响应式数据
const loading = ref(false);

// 搜索表单
const searchForm = ref({});

// 搜索参数对象
const searchOptions = ref({
  orderNo: '', // 订单编号搜索
  doctorName: '', // 康复师姓名搜索
  reservationStatus: undefined as number | undefined, // 订单状态搜索
});

// 状态选项
const statusOptions = ref([
  { label: '待付款', value: -1 },
  { label: '待确定', value: 0 },
  { label: '已确认', value: 1 },
  { label: '已完成', value: 2 },
  { label: '已取消', value: 3 },
]);

// 表格数据
const tableData = ref<OrderResponse[]>([]);

// 订单统计数据
const orderStats = ref<OrderStats>({
  totalCount: 0,
  totalAmount: 0,
});

// 分页配置
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
});

// 状态相关方法
const getStatusText = (status: number) => {
  const statusMap = {
    '-1': '待付款',
    '0': '待确定',
    '1': '已确认',
    '2': '已完成',
    '3': '已取消',
  };
  return statusMap[status.toString()] || '未知状态';
};

// Element Plus 标签类型映射
const getStatusType = (status: number) => {
  const typeMap = {
    '-1': 'info', // 待付款 - 灰色
    '0': 'warning', // 待确定 - 橙色
    '1': 'success', // 已确认 - 绿色
    '2': 'success', // 已完成 - 绿色
    '3': 'danger', // 已取消 - 红色
  };
  return typeMap[status.toString()] || 'default';
};

// 防抖函数
const debounce = (func: Function, delay: number) => {
  let timeoutId: NodeJS.Timeout;
  return (...args: any[]) => {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => func.apply(null, args), delay);
  };
};

// 分 → 元，去掉尾部无意义的 0
const formatPrice = (cents?: number | string | null): string => {
  if (cents == null || cents === '' || Number.isNaN(cents)) return '0';
  const y = Number(cents) / 100; // 转元
  if (!Number.isFinite(y)) return '0'; // 防 Infinity/NaN
  return y
    .toFixed(2) // 先保留 2 位
    .replace(/\.?0+$/, '') // 去掉小数点后全 0
    .replace(/\.$/, ''); // 如果小数点成孤儿，也删掉
};

// 获取订单统计数据
const fetchOrderStats = async () => {
  try {
    const response = await getOrderStats();
    orderStats.value = response.data.data;
  } catch (error) {
    console.error('获取订单统计数据失败:', error);
    ElMessage.error(error.message || '获取统计数据失败');
  }
};

// 数据获取方法
const fetchData = async () => {
  try {
    loading.value = true;

    // 构建查询参数
    const params: OrderRequest = {
      pageNum: pagination.value.current,
      pageSize: pagination.value.pageSize,
    };

    // 添加订单编号搜索
    if (searchOptions.value.orderNo && searchOptions.value.orderNo.trim()) {
      params.orderNo = searchOptions.value.orderNo.trim();
    }

    // 添加康复师姓名搜索
    if (searchOptions.value.doctorName && searchOptions.value.doctorName.trim()) {
      params.doctorName = searchOptions.value.doctorName.trim();
    }

    // 添加状态筛选
    if (searchOptions.value.reservationStatus !== undefined) {
      params.reservationStatus = searchOptions.value.reservationStatus;
    }

    // 调用API获取数据
    const response = await getOrderList(params);
    tableData.value = response.data.data.records || [];
    console.log('tableData', tableData.value);
    pagination.value.total = response.data.data.total || 0;
  } catch (error: any) {
    console.error('获取订单列表失败:', error);
    ElMessage.error(error.message || '获取数据失败');
  } finally {
    loading.value = false;
  }
};

// 搜索方法
const handleSearch = () => {
  pagination.value.current = 1; // 重置到第一页
  fetchData();
};

// 创建防抖的搜索函数
const debouncedSearch = debounce(handleSearch, 400);

// 分页大小变化处理
const handleSizeChange = (val: number) => {
  pagination.value.pageSize = val;
  pagination.value.current = 1;
  fetchData();
};

// 当前页变化处理
const handleCurrentChange = (val: number) => {
  pagination.value.current = val;
  fetchData();
};

// 监听搜索条件变化，实现实时搜索
watch(
  [() => searchOptions.value.orderNo, () => searchOptions.value.doctorName],
  () => {
    // 使用防抖搜索
    debouncedSearch();
  },
  { deep: true },
);

// 页面加载时获取数据
onActivated(() => {
  fetchOrderStats(); // 获取订单统计数据
  fetchData(); // 获取列表数据
});

// 订单详情弹窗相关
const detailVisible = ref(false);
const currentOrder = ref<OrderResponse | null>(null);

// 操作方法
const handleView = async (row: OrderResponse) => {
  console.log('查看订单详情:', row);
  try {
    // 重新获取订单详情信息
    const response = await getOrderDetail(row.id);
    currentOrder.value = response.data.data;

    // 显示详情弹窗
    detailVisible.value = true;
  } catch (error: any) {
    console.error('获取订单详情失败:', error);
    ElMessage.error(error.message || '获取订单详情失败');
  }
};

// 处理详情弹窗关闭
const handleDetailClose = () => {
  detailVisible.value = false;
  currentOrder.value = null;
};

// 刷新数据
const handleRefresh = () => {
  pagination.value.current = 1;
  fetchOrderStats(); // 刷新订单统计数据
  fetchData(); // 刷新列表数据
};

// 重置筛选条件
const handleReset = () => {
  // 重置所有筛选条件
  searchOptions.value = {
    orderNo: '',
    doctorName: '',
    reservationStatus: undefined,
  };

  // 重置分页到第一页
  pagination.value.current = 1;

  // 重新获取数据
  fetchData(); // 刷新列表数据
};
</script>

<style scoped lang="less">
.order-page {
  min-height: 100vh;

  // 统计卡片区域样式
  .stats-section {
    margin-bottom: 24px;

    .stat-card {
      height: 90px;
      border-radius: 8px;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
      }

      // 总订单数卡片样式
      &.total-card {
        border-left: 4px solid #409eff;
      }

      // 总金额卡片样式
      &.amount-card {
        border-left: 4px solid #67c23a;
      }
    }
  }

  // 筛选和搜索区域样式
  .filters-section {
    margin-bottom: 16px;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

    .el-form {
      .el-form-item {
        margin-right: 20px;
        margin-bottom: 0;

        &:last-child {
          margin-right: 0;
        }

        .el-form-item__label {
          font-size: 14px;
          color: #6b7280;
          font-weight: 500;
        }
      }
    }
  }

  // 表格区域样式
  .table-section {
    .table-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      h3 {
        margin: 0;
        font-size: 16px;
        font-weight: 600;
        color: #1f2937;
      }
    }

    // 操作按钮样式
    .operation-buttons {
      display: flex;
      gap: 4px;
      flex-wrap: nowrap;
      align-items: center;

      .el-button {
        white-space: nowrap;
        min-width: auto;
      }
    }
  }
}
</style>
